<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"  @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="任务名称" prop="jobName">
          <t-input v-model="params.jobName" placeholder="请输入任务名称" clearable />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="处理器的名字" prop="handlerName">
          <t-input v-model="params.handlerName" placeholder="请输入处理器的名字" clearable />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="执行状态" prop="status">
          <t-select v-model="params.status" placeholder="请选择执行状态" clearable filterable
            :options="dictionaryStore.get('infra_job_log_status')" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="开始执行时间" prop="beginTime">
          <t-date-picker 
            allow-input 
            v-model="params.beginTime"
            clearable
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="结束执行时间" prop="endTime">
          <t-date-picker
            allow-input 
            v-model="params.endTime"
            clearable
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table ref="customTableRef" row-key="id" :columns="columns" :api="jobLogCRUD.page"
      column-controller-key="SystemJobLogList">
      <template #status="{ row }">
        <t-tag variant="light" :theme="getTimelineDotColor(row.status)">{{
          dictionaryStore.analysis('infra_job_log_status', row.status)
          }}</t-tag>
      </template>
      <template #duration="{ row }">
        {{ row.duration + ' 毫秒' }}
      </template>
      <template #beginTime="{ row }">
        {{ dayjs(row.beginTime).format('YYYY-MM-DD HH:mm:ss') + '~' + dayjs(row.endTime).format('YYYY-MM-DD HH:mm:ss')
        }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link v-permission="['infra:job:query']" theme="primary" @click="handleOpenDialog('read', { id: row.id })">
            详情
          </t-link>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog ref="customDialogRef" v-slot="{ formData, readonly }" :api-map="jobLogCRUD" header="*调度日志">
      <t-form-item label="任务编号">
        {{ formData.jobId }}
      </t-form-item>
      <t-form-item label="处理器的名字">
        {{ formData.handlerName }}
      </t-form-item>
      <t-form-item label="处理器的参数">
        {{ formData.handlerParam }}
      </t-form-item>
      <t-form-item label="第几次执行">
        {{ formData.executeIndex }}
      </t-form-item>
      <t-form-item label="执行时间">
        {{ dayjs(formData.beginTime).format('YYYY-MM-DD HH:mm:ss') + '~' + dayjs(formData.endTime).format('YYYY-MM-DD HH:mm:ss')
        }}
      </t-form-item>
      <t-form-item label="执行时长">
        {{ formData.duration + ' 毫秒' }}
      </t-form-item>
      <t-form-item label="任务状态">
        <t-tag variant="light" :theme="getTimelineDotColor(formData.status)">{{
          dictionaryStore.analysis('infra_job_log_status', formData.status)
          }}</t-tag>
      </t-form-item>
      <t-form-item label="执行结果">
        {{ formData.result }}
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>
<script lang="ts">
export default {
  name: 'SystemJobLog',
};
</script>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { DialogPlugin, MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, ref, useTemplateRef } from 'vue';
import { useRoute } from 'vue-router';

import { jobLogCRUD, cleanJobLog } from '@/api/system/job-log';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// 路由
const route = useRoute();

// columns
const columns: TableCol[] = [
  { colKey: 'id', title: '日志编号' },
  { colKey: 'jobId', title: '任务编号' },
  { colKey: 'handlerName', title: '处理器的名字' },
  { colKey: 'handlerParam', title: '处理器的参数' },
  { colKey: 'executeIndex', title: '第几次执行' },
  { colKey: 'beginTime', title: '执行时间', width: 220 },
  { colKey: 'duration', title: '执行时长' },
  { colKey: 'status', title: '任务状态' },
  { colKey: 'operation', title: '操作', width: 120 },
];

// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  // 处理时间
  if (params.beginTime) {
    params.beginTime = dayjs(params.beginTime).format('YYYY-MM-DD HH:mm:ss');
  }
  if (params.endTime) {
    params.endTime = dayjs(params.endTime).format('YYYY-MM-DD HH:mm:ss');
  }
  // 如果是从任务列表跳转过来，需要带上任务编号
  if (route.query.id) {
    params.jobId = route.query.id;
  }
  customTableRef.value.initTable(params);
};

// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};

onMounted(() => {
  handleInitTable();
});

// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'read', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};


// 处理清空
const handleClean = () => {
  const dialog = DialogPlugin({
    header: '确认清空',
    body: '是否确认清空所有调度日志数据？',
    onConfirm: async () => {
      await cleanJobLog();
      MessagePlugin.success('清空成功');
      handleRefreshTable();
      dialog.hide();
    },
  });
};

const getTimelineDotColor = (result: number): 'default' | 'primary' | 'success' | 'danger' | 'warning' => {
  const map: ('primary' | 'success' | 'danger')[] = [
    'primary', 'success', 'danger'
  ]
  return result in map ? map[result] : 'default'
}
</script>